<template>
    <div class="view-account">
        <div class="view-account-header"></div>

        <div class="view-account-container">
            <div class="view-account-top">
                <img src="/logo.png" />
                <span>{{ systemName }}</span>
            </div>

            <div class="view-account-form">
                <n-tabs justify-content="space-evenly" size="large">
                    <n-tab-pane name="password" tab="密码登录">
                        <n-form>
                            <n-form-item-row>
                                <n-input
                                    v-model:value="data.phone"
                                    size="large"
                                    type="text"
                                    maxlength="11"
                                    placeholder="请输入电话号码"
                                    clearable
                                >
                                    <template #prefix>
                                        <n-icon
                                            :size="iconSize"
                                            color="#808695"
                                        >
                                            <Person />
                                        </n-icon>
                                    </template>
                                </n-input>
                            </n-form-item-row>

                            <n-form-item-row>
                                <n-input
                                    v-model:value="data.password"
                                    size="large"
                                    type="password"
                                    show-password-toggle
                                    placeholder="请输入登录密码"
                                    clearable
                                >
                                    <template #prefix>
                                        <n-icon
                                            :size="iconSize"
                                            color="#808695"
                                        >
                                            <LockClosed />
                                        </n-icon>
                                    </template>
                                </n-input>
                            </n-form-item-row>
                        </n-form>

                        <n-button
                            type="primary"
                            @click="handlePasswordLogin"
                            block
                        >
                            登录
                        </n-button>
                    </n-tab-pane>

                    <n-tab-pane name="smscode" tab="验证码登录">
                        <n-form>
                            <n-form-item-row>
                                <n-input
                                    v-model:value="data.phone"
                                    size="large"
                                    type="text"
                                    maxlength="11"
                                    placeholder="请输入电话号码"
                                    clearable
                                >
                                    <template #prefix>
                                        <n-icon
                                            :size="iconSize"
                                            color="#808695"
                                        >
                                            <Person />
                                        </n-icon>
                                    </template>
                                </n-input>
                            </n-form-item-row>

                            <n-form-item-row>
                                <n-input
                                    v-model:value="data.code"
                                    size="large"
                                    placeholder="请输入验证码"
                                    clearable
                                >
                                    <template #prefix>
                                        <n-icon
                                            :size="iconSize"
                                            color="#808695"
                                        >
                                            <LockClosed />
                                        </n-icon>
                                    </template>

                                    <template #suffix>
                                        <n-button
                                            type="primary"
                                            :disabled="smsCodeBtn.disabled"
                                            @click="handleSmsCode"
                                        >
                                            {{ smsCodeBtn.text }}
                                        </n-button>
                                    </template>
                                </n-input>
                            </n-form-item-row>
                        </n-form>

                        <n-button
                            type="primary"
                            @click="handleSmsCodeLogin"
                            block
                        >
                            登录
                        </n-button>
                    </n-tab-pane>
                </n-tabs>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { reactive, ref } from "vue"
    import { useStore } from "vuex"
    import { useRouter } from "vue-router"
    import { Person, LockClosed } from "@vicons/ionicons5"

    import { systemName, iconSize } from "@/utils/config"
    import { validatePhone } from "@/utils/validate"
    import { login, getSmsCode, getInfo, getMenus } from "./api"

    const store = useStore()
    const router = useRouter()

    const data = reactive({
        phone: "",
        password: "",
        code: "",
    })

    const smsCodeBtn = reactive({
        disabled: false,
        duration: 60,
        text: "获取验证码",
    })

    const handleSmsCode = () => {
        const { phone } = data

        if (phone) {
            if (!validatePhone(phone)) {
                window.$message.error("电话号码错误")

                return
            }
        } else {
            window.$message.info("请输入电话号码")

            return
        }

        smsCodeBtn.disabled = true
        smsCodeBtn.text = `获取验证码（${smsCodeBtn.duration}s）`

        const id = setInterval(() => {
            smsCodeBtn.duration -= 1

            if (smsCodeBtn.duration <= 0) {
                clearInterval(id)

                smsCodeBtn.disabled = false
                smsCodeBtn.duration = 60
                smsCodeBtn.text = "获取验证码"
            } else {
                smsCodeBtn.text = `获取验证码（${smsCodeBtn.duration}s）`
            }
        }, 1000)

        getSmsCode(phone).then(async (response) => {
            window.$message.success("验证码已发送")
        })
    }

    const handlePasswordLogin = () => {
        const { phone, password } = data

        if (phone) {
            if (!validatePhone(phone)) {
                window.$message.error("电话号码错误")

                return
            }
        } else {
            window.$message.info("请输入电话号码")

            return
        }

        if (!password) {
            window.$message.info("请输入登录密码")

            return
        }

        login({ phone, password }).then(async (response) => {
            store.commit("login", response.token)
            updateUserInfo()
        })
    }

    const handleSmsCodeLogin = () => {
        const { phone, code } = data

        if (phone) {
            if (!validatePhone(phone)) {
                window.$message.error("电话号码错误")
            }
        } else {
            window.$message.info("请输入电话号码")
        }

        if (!phone) {
            window.$message.info("请输入电话号码")

            return
        }

        if (!validatePhone(phone)) {
            window.$message.error("电话号码错误")

            return
        }

        if (!code) {
            window.$message.info("请输入验证码")

            return
        }

        login({ phone, code }).then(async (response) => {
            store.commit("login", response.token)
            updateUserInfo()
        })
    }

    function updateUserInfo() {
        getInfo().then(async (response) => {
            store.commit("updateInfo", response)

            getMenus().then(async (_response) => {
                const menus: any = {}

                _response.data.forEach((obj: any) => {
                    menus[obj.name] = obj.label
                })

                store.commit("updateMenus", menus)

                const path = router.currentRoute.value.query.origin || "/"
                router.push({ path: path as string })
            })
        })
    }
</script>

<style lang="less" scoped>
    .view-account {
        display: flex;
        flex-direction: column;

        height: 100vh;
        overflow: auto;
        background-image: url("@/assets/login.svg");
        background-size: 100% auto;

        &-container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            margin: auto auto;
            padding: 20px;
            width: 400px;
            max-width: 80%;
        }

        &-top {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 40px 0;

            img {
                width: 64px;
                height: 64px;
            }

            span {
                font-size: 28px;
                font-weight: 300;
                padding-left: 20px;
            }
        }

        &-form {
            display: flex;
            width: 100%;
        }
    }
</style>
